﻿using Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Services.Client;

/// <summary>
/// 客户地址管理
/// </summary>
[Authorize]
[ApiDescriptionSettings("收货地址")]
public class AddressServices : BaseServices<Entity.ClientAddress>
{
    private readonly ISqlSugarClient db;

    /// <summary>
    /// 客户端地址管理
    /// </summary>
    /// <param name="db"></param>
    public AddressServices(ISqlSugarClient db) : base(db)
    {
        this.db = db;
    }

    /// <summary>
    /// 获取地址
    /// </summary>
    /// <returns></returns>
    public override async Task<object> GetPage()
    {

        string search = SearchStr;

        var data = await db.Queryable<ClientAddress>()

            .WhereIF(search.Length > 0, search)

            .Where(x => x.UserId == USERID)

            .OrderByDescending(x => x.Id)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);

    }

    /// <summary>
    /// 编辑添加地址
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public override async Task<object> Edit(ClientAddress t)
    {
        t.UserId = USERID;

        return await base.Edit(t);
    }

    /// <summary>
    /// 设置为默认地址
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> SetDefault(int id)
    {
        bool state = await db.Updateable<ClientAddress>()

            .Where(x => x.UserId == USERID)

            .SetColumns(x => x.Default == false)

            .ExecuteCommandHasChangeAsync();

        bool state2 = await db.Updateable<ClientAddress>()

           .Where(x => x.UserId == USERID && x.Id == id)

           .SetColumns(x => x.Default == true)

           .ExecuteCommandHasChangeAsync();

        return Msg(state && state2);
    }

    /// <summary>
    /// 获取默认地址
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetDefaultAddress()
    {
        var data = await db.Queryable<Entity.ClientAddress>().FirstAsync(x => x.UserId == USERID && x.Default);

        return Ok(data);
    }
}
